﻿using Exam.BLL;
using Exam.DBHelper;
using Exam.Model;
using ExaminationWeb.Common;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace ExaminationWeb.Controllers
{
    public class ModalityController : Controller
    {
        //
        // GET: /Modality/
        ModalityService modalityService = new ModalityService();
        public ActionResult ModalityList()
        {
            return View();
        }
        public ActionResult ModalityAdd()
        {
            return View();
        }
        public ActionResult ModalityUpdate(string id)
        {
            Modality modality = modalityService.LoadEntites(e => e.ModalityID == Guid.Parse(id)).First();
            ViewData["Modality"] = modality;
            return View();
        }
        #region 页面事件
        public JsonResult GetAllInfos()
        {
            int pageIndex = Request["sEcho"] == null ? 1 : int.Parse(Request["sEcho"]);
            int pageSize = Request["iDisplayLength"] == null ? 15 : int.Parse(Request["iDisplayLength"]);
            int pageStart = Request["iDisplayStart"] == null ? 0 : int.Parse(Request["iDisplayStart"]);

            string SortDirindex = Request["iSortCol_0"] == null ? "" : Request["iSortCol_0"];
            string SortDir = "";
            string DataProp = "";
            if (!string.IsNullOrEmpty(SortDirindex))
            {
                DataProp = Request["mDataProp_" + SortDirindex] == null ? "" : Request["mDataProp_" + SortDirindex];
                SortDir = Request["sSortDir_0"] == null ? "" : Request["sSortDir_0"]; //asc or desc
            }
            int totalcount = 0;
            string modalityName = Request["modalityName"] == null ? "" : Request["modalityName"];
            string modalityCode = Request["modalityCode"] == null ? "" : Request["modalityCode"];
            string modalityType = Request["modalityType"] == "-1" ? "" : Request["modalityType"];
            string isdelete = Request["isactive"] == "-1" ? "" : Request["isactive"];

            var predicate = PredicateBuilder.True<Modality>();
            if(!string.IsNullOrEmpty(modalityCode))
            {
                predicate = predicate.And(e => e.ModalityCode.ToLower().Contains(modalityCode.ToLower()));
            }

            if(!string.IsNullOrEmpty(modalityName))
            {
                predicate = predicate.And(e=>e.ModalityName.ToLower().Contains(modalityName.ToLower()));
            }

            if(!string.IsNullOrEmpty(modalityType))
            {
                predicate = predicate.And(e => e.ModalityType.Equals(int.Parse(modalityType)));
            }

            if (!string.IsNullOrEmpty(isdelete))
            {
                predicate = predicate.And(e => e.IsActive.Equals(int.Parse(isdelete)));
            }

            Func<Modality, bool> x = predicate.Compile() as Func<Modality, bool>;
            IQueryable<Modality> data = modalityService.LoadEntites(x, DataProp, SortDir == "asc", pageStart, pageSize, out totalcount);

            var result = new { iTotalDisplayRecords = totalcount, iTotalRecords = totalcount, aaData = data, sEcho = 0 };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public string AddInfo(Modality modality)
        {
            try
            {
                if (IsExistData(modality).ModalityID.ToString() == "00000000-0000-0000-0000-000000000000")
                {
                    modality.ModalityID = Guid.NewGuid();
                    modality.ModalityCode = GenerateRandomString(UserAccount.UserID.ToString());
                    DateTime time = DateTime.Now;
                    modality.CreateTime = time;
                    modality.CreateUserID = UserAccount.UserID;
                    modality.UpdateTime = time;
                    Modality newModality = modalityService.AddEntity(modality);

                    return newModality.ModalityID.ToString();
                }
                else
                {
                    return "repeat";
                }

            }
            catch (Exception e)
            {
                return "";
            }
        }
        [HttpPost]
        public string UpdateInfo(Modality modality)
        {
            try
            {
                Modality _modality = IsExistData(modality);
                if (_modality.ModalityID.ToString() == "00000000-0000-0000-0000-000000000000")
                {
                    modality.UpdateTime = DateTime.Now;
                    modality.UpdateUserID = UserAccount.UserID;
                    modalityService.UpdateEntity(modality);
                    return "suc";
                }
                else
                {
                    return "repeat";
                }
            }
            catch (Exception e)
            {
                return "err";
            }
        }
        #endregion
        #region 公用
        public Modality IsExistData(Modality modality)
        {            
            SQLHelper commonservice = new SQLHelper();
            Dictionary<string, SqlParameter> dic = new Dictionary<string, SqlParameter>();

            SqlParameter parname = new SqlParameter("@ModalityName", System.Data.SqlDbType.NVarChar);
            parname.Value = modality.ModalityName;
            dic.Add("ModalityName", parname);
            SqlParameter type = new SqlParameter("@ModalityType", System.Data.SqlDbType.Int);
            type.Value = modality.ModalityType;
            dic.Add("ModalityType", type);
            return commonservice.getExistData<Modality>("Modality", dic);
        }
        #endregion
        private string GenerateRandomString(string userId)
        {
            var guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 8);
            var md5h = MD5Hash(userId + DateTime.Now.Ticks, false);

            return guid + md5h;
        }
        private string MD5Hash(string target, bool use16Byte)
        {
            if (use16Byte) //16位MD5加密（取32位加密的9~25字符） 
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(target, "MD5").ToLower().Substring(8, 16);

            }
            else//32位加密 
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(target, "MD5").ToLower();

            }
        } 


    }
}
